<template>
  <div ref="workbench" class="crm-workbench">
    <div class="head">
      <flexbox class="head__body">
        <time-type-select
          :width="190"
          default-type="month"
          @change="timeTypeChange"
        />
  
          <el-select v-model="company" placeholder="请选择" @change="changeFn" size="medium" style="margin-right:20px">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        
          <!-- <div class="lable">部门：</div> -->
          <xh-structure-cell
            radio
            class="xh-structure-cell"
            @value-change="structureChange"
            type="1"
          />
  
        <!-- <el-button class="sort-btn" icon="wk wk-manage" @click="setSortShow = true" /> -->
      </flexbox>
    </div>
    <div class="crm-workbench__body">
      <div v-loading="loading" class="brief-box">
        <div class="brief-title">
          <span class="icon wk wk-briefing" />
          <span class="text">销售部数据统计</span>
        </div>
        <div class="brief">
          <flexbox
            v-for="(item, index) in briefList"
            :key="index"
            :span="2"
            class="brief-item"
            @click.native="reportClick(item)"
          >
            <flexbox class="brief-item__body">
              <!-- <div :style="{ backgroundColor: item.color }" class="icon-box">
                <span :class="item.icon" class="icon wk" />
              </div> -->
              <div class="info">
                <div class="title" v-if="!item.notConverted">
                  {{ item.label }}
                </div>
                <div
                  v-if="!item.notConverted"
                  v-fit-text="{ fontSize: 24 }"
                  class="number"
                >
                  {{ item.num }}
                </div>
              </div>
            </flexbox>
            <div class="brief-item__others" v-if="item.textValue">
              <div class="text">
                {{ item.notConverted ? "客服总数" : item.text }}
              </div>
              <div :class="item.status" class="rate text-one-line">
                <span class="rate__num">{{
                  item.notConverted
                    ? item.num
                    : item.textValue == -1
                    ? "0"
                    : item.textValue
                }}</span>
                <span :class="`el-icon-${item.status}`" class="rate__icon" />
              </div>
            </div>
            <div class="brief-item__others" v-if="item.notConverted">
              <div class="text">未转化</div>
              <div :class="item.status" class="rate text-one-line">
                <span class="rate__num">{{
                  item.notConverted == -1 ? "0" : item.notConverted
                }}</span>
                <span :class="`el-icon-${item.status}`" class="rate__icon" />
              </div>
            </div>
            <div
              v-if="rateText !== '' && !item.notConverted"
              class="brief-item__others"
            >
              <div class="text">{{ rateText }}</div>
              <div :class="item.status" class="rate text-one-line">
                <span class="rate__num">{{ item.rate }}</span>
                <span :class="`el-icon-${item.status}`" class="rate__icon" />
              </div>
            </div>
            <div v-if="item.notConverted" class="brief-item__others">
              <div class="text">已转化</div>
              <div :class="item.status" class="rate text-one-line">
                <span class="rate__num">{{
                  item.textValue == -1 ? "0" : item.textValue
                }}</span>
                <span :class="`el-icon-${item.status}`" class="rate__icon" />
              </div>
            </div>
          </flexbox>
        </div>
      </div>

      <flexbox class="section" align="stretch">
        <div class="left">
          <component
            v-for="(item, index) in sortLeft"
            :key="index"
            :is="item"
            :dataForm="company"
            :deptId="deptId"
            :filter-value="filterValue"
            class="right-content"
            @chart-click="chartClick"
          />
        </div>
        <div class="right">
          <component
            v-for="(item, index) in sortRight"
            :key="index"
            :is="item"
            :filter-value="filterValue"
            class="right-content"
            @chart-click="chartClick"
          />
        </div>
      </flexbox>
      <flexbox>
        <SaleStatistics :filter-value="filterValue" class="right-content" @chart-click="chartClick"></SaleStatistics>
      </flexbox>
    </div>

    <!-- 销售简报列表 -->
    <report-list
      :show.sync="reportListShow"
      :title="reportData.title"
      :placeholder="reportData.placeholder"
      :crm-type="reportData.crmType"
      :request="reportData.request"
      :record-request="reportData.recordRequest"
      :params="reportData.params"
      :field-list="fieldReportList"
      :paging="reportData.paging"
      :sortable="reportData.sortable"
    />
    <!-- 
    排序
    <set-sort
      v-if="setSortShow"
      :visible.sync="setSortShow"
    @save="getModelSort" />-->

    <!-- 员工部门选择 -->
    <members-dep-dialog
      :visible.sync="membersDepVisible"
      :user-checked-data="filterValue.users"
      :dep-checked-data="filterValue.strucs"
      radio
      @close="membersDepCancel"
      @confirm="membersDepSelect"
    />
  </div>
</template>

<script>
import {
  crmQueryBulletinAPI,
  crmIndexIndexListAPI,
  crmQueryRecordConuntAPI,
  crmIndexGetRecordListAPI,
  crmIndexSortAPI,
  crmInstrumentSellFunnelBusinessListAPI,
} from "@/api/crm/workbench";

import PerformanceChart from "./components/PerformanceChart";
import RankingStatistics from "./components/RankingStatistics";
import TimeTypeSelect from "@/components/TimeTypeSelect";
import ReportList from "./components/ReportList";
import MembersDepDialog from "@/components/SelectEmployee/MembersDepDialog";
import { mapGetters } from "vuex";
import { separator } from "@/filters/vueNumeralFilter/filters";
import FitText from "@/directives/fitText";
import Lockr from "lockr";
import XhStructureCell from "@/components/CreateCom/XhStructureCell";
import SaleStatistics from "./components/SaleStatistics";

/**
 * TODO 2、员工部门筛选选择，
 *      3、员工部门筛选后刷新销售简报数据
 */

export default {
  name: "Workbench",
  directives: {
    FitText,
  },
  components: {
    RankingStatistics, // 7 排行榜
    PerformanceChart, // 4 业绩指标完成率 (回款金额)
    TimeTypeSelect,
    ReportList,
    MembersDepDialog,
    XhStructureCell,
    SaleStatistics
  },
  data() {
    return {
      briefList: [
        {
          label: "当前学员数",
          title: "当前学员数",
          plaTip: "leadsTip",
          type: "customer",
          labelValue: 1,
          field: "customerData",
          icon: "wk-customer-solid",
          num: "",
          rate: "",
          status: "",
          color: "#2362FB",
          text: "转化率",
          textValue: "",
          notConverted: "",
        },
        {
          label: "客服加微信数",
          title: "客服加微信数",
          plaTip: "leadsTip",
          type: "contacts",
          labelValue: 1,
          field: "addWechatData",
          icon: "wk-customer",
          num: "",
          rate: "",
          status: "",
          color: "#27BA4A",
          text: "转化率",
          textValue: "",
          searchList: [
            {
              type: 1,
              values: ["是"],
              formType: "select",
              name: "fliedWdwsqb",
            },
          ],
        },
        {
          label: "客服报课",
          title: "客服报课",
          plaTip: "leadsTip",
          type: "business",
          labelValue: 1,
          field: "customerApplyData",
          icon: "wk-record",
          num: "",
          rate: "",
          status: "",
          color: "#FB9323",
          text: "转化率",
          textValue: "",
          searchList: [
            {
              type: 1,
              values: ["是"],
              formType: "select",
              name: "fliedDkiojd",
            },
          ],
        },
        {
          label: "销售加微信数",
          title: "销售加微信数",
          plaTip: "customerTip",
          type: "contract",
          labelValue: 2,
          field: "salesAddWechatData",
          icon: "wk-customer-solid",
          num: "",
          rate: "",
          status: "",
          color: "#4A5BFD",
          text: "转化率",
          textValue: "",
          searchList: [
            {
              type: 1,
              values: ["是"],
              formType: "select",
              name: "isAddService",
            },
          ],
        },
        {
          label: "进群学员数",
          title: "进群学员数",
          plaTip: "customerTip",
          type: "contract",
          labelValue: 2,
          field: "customerJoinGroupData",
          icon: "wk-receivables",
          num: "",
          rate: "",
          status: "",
          color: "#19B5F6",
          text: "转化率",
          textValue: "",
          searchList: [
            {
              type: 1,
              values: ["是"],
              formType: "select",
              name: "fliedXjimto",
            },
          ],
        },
        {
          label: "销售学员成交数",
          title: "销售学员成交数",
          plaTip: "customerTip",
          type: "business",
          labelValue: 2,
          field: "dealSuccessfulData",
          icon: "wk-icon-opportunities",
          num: "",
          rate: "",
          status: "",
          color: "#AD5CFF",
          text: "成交率",
          textValue: "",
          searchList: [
            {
              type: 1,
              values: ["1"],
              formType: "dealStatus",
              name: "dealStatus",
            },
          ],
        }
      ],
      options: [
        { label: "涵品", id: 1 },
        { label: "有成", id: 2 },
      ],
      company: 1,
      deptId:'',
      rangeOptions: [
        { label: "全公司", command: 5 },
        { label: "仅本部门", command: 3 },
        { label: "仅本人", command: 1 },
        { label: "本部门及下属部门", command: 4 },
        { label: "本人及下属", command: 2 },
        { label: "渠道销售情况", command: 6 },
      ],
      membersDepVisible: false,
      filterDataType: 5,
      filterValue: {
        dataType: 5,
        users: [],
        strucs: [],
        dataForm: 1,
        deptId:"",
        timeLine: {
          type: "default",
          value: "month",
        },
      },

      loading: false,

      reportListShow: false,
      fieldReportList: null,
      reportData: {
        title: "",
        placeholder: "",
        crmType: "",
        request: null,
        recordRequest: crmIndexGetRecordListAPI,
        params: null,
        paging: true,
        sortable: false,
        crmLable: "",
      },

      // 排序
      sortLeft: ["RankingStatistics"],
      sortRight: ["PerformanceChart"],
      setSortShow: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo", "collapse"]),
    // 如果只筛选一个人则头像显示当前被筛选人的头像，否则显示默认错误头像
    avatarData() {
      if (this.filterValue.dataType === "custom") {
        const users = this.filterValue.users || [];
        if (users.length) {
          return users[0];
        }
        const strucs = this.filterValue.strucs || [];
        if (strucs.length) {
          return {
            realname: strucs[0].name,
            img: "",
          };
        }
      }

      if (this.filterValue.dataType == 1) {
        return this.userInfo;
      }
      return {
        showIcon: true,
        realname: {
          1: "仅本人",
          2: "本人及下属",
          3: "仅本部门",
          4: "本部门及下属部门",
        }[this.filterValue.dataType],
      };
    },
    // 销售简报百分比提示语
    rateText() {
      // console.log(this.filterValue.timeLine);
      if (this.filterValue.timeLine.type === "custom") return "";
      const type = this.filterValue.timeLine.value || "month";
      return (
        {
          today: "环比昨天",
          yesterday: "环比前天",
          month: "环比上月",
          lastMonth: "环比",
        }[type] || ""
      );
    },
    rateText1() {
      if (this.filterValue.timeLine.type === "custom") return "";
      const type = this.filterValue.timeLine.value || "today";
      return (
        {
          today: "转化率",
          yesterday: "成交率",
          month: "复购率",
        }[type] || ""
      );
    },
  },
  watch: {
    collapse() {
      setTimeout(() => {
        this.$bus.emit("window-resize");
      }, 300);
    },
    filterDataType() {
      this.getBriefData();
    },
    filterValue: {
      handler() {
        this.getBriefData();
      },
      deep: true,
    },
  },
  created() {
    const oldDataType = Lockr.get("crmWorkbenchRangeFilter");
    if (oldDataType) {
      this.filterDataType = oldDataType;
      this.filterValue.dataType = oldDataType;
    }
    this.getBriefData();
    // this.getModelSort()
  },
  mounted() {
    this.$nextTick(() => {
      window.addEventListener("resize", this.resizeFn);
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeFn);
    this.$bus.off("window-resize");
  },
  methods: {
    /**
     * 窗口尺寸发生改变实时调整 EChart 尺寸
     */
    changeFn(e) {
      this.company = e;
      this.filterValue.dataForm = e;
    },
    resizeFn() {
      if (this.timer) return;
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.timer = null;
      }, 30);
      this.$bus.emit("window-resize");
    },

    timeTypeChange(data) {
      // console.log(data)
      this.filterValue.timeLine = data;
    },
structureChange(e){
this.filterValue.deptId = e.value[0].deptId;
this.deptId = e.value[0].deptId;
delete this.filterValue.timeLine
},
    radioMenuSelect() {
      console.log(this.filterDataType, "笑死");
      if (this.filterDataType != "custom") {
        Lockr.set("crmWorkbenchRangeFilter", this.filterDataType);
        this.filterValue.dataType = this.filterDataType;
      } else {
        this.membersDepVisible = true;
      }
    },

    /**
     * 选择员工和部门
     */
    membersDepSelect(users, strucs) {
      if (!users.length && !strucs.length) {
        this.filterDataType = 1;
        this.filterValue.dataType = 1;
        this.filterValue.users = [];
        this.filterValue.strucs = [];
      } else {
        this.filterValue.dataType = 5;
        this.filterValue.users = users;
        this.filterValue.strucs = strucs;
      }
    },

    membersDepCancel(users, strucs) {
      if (this.filterValue.dataType != 5) {
        this.filterDataType = this.filterValue.dataType;
        this.filterValue.users = [];
        this.filterValue.strucs = [];
      }
    },

    /**
     * 员工部门选择
     */
    // userStrucSelect(users, strucs) {
    //   if (!users.length && !strucs.length) {
    //     this.filterValue.users = [this.userInfo]
    //     this.filterValue.strucs = []
    //   } else {
    //     this.filterValue.users = users
    //     this.filterValue.strucs = strucs
    //   }
    // },

    /**
     * 获取请求参数
     */
    getBaseParams() {
      const params = {};
      params.dataForm = this.company == 1 ? "涵品" : "有成";
      if (this.filterDataType != "custom") {
        params.dataType = this.filterDataType;
      } else {
        if (this.filterValue.strucs.length) {
          params.isUser = 0;
          params.deptId = this.filterValue.strucs[0].id;
        } else {
          params.isUser = 1;
          params.userId = this.filterValue.users.length
            ? this.filterValue.users[0].userId
            : "";
        }
      }

      if (this.filterValue.timeLine.type) {
        if (this.filterValue.timeLine.type === "custom") {
          params.startTime = this.filterValue.timeLine.startTime.replace(
            /\./g,
            "-"
          );
          params.endTime = this.filterValue.timeLine.endTime.replace(
            /\./g,
            "-"
          );
        } else {
          params.type = this.filterValue.timeLine.value || "";
        }
      }
      console.log(params, "参数是啥");
      return params;
    },
    /**
     * 获取销售简报数据
     */
    getBriefData() {
      this.loading = true;

      crmQueryBulletinAPI(this.getBaseParams())
        .then((res) => {
          this.loading = false;
          let arr = Object.keys(res.data);
          for (var i = 0; i < this.briefList.length; i++) {
            for (var k = 0; k < arr.length; k++) {
              if (res.data[arr[k]] !== null) {
                if (this.briefList[i].field == arr[k]) {
                  // console.log(arr[k])
                  this.briefList[i].rate = res.data[arr[k]].mom;
                  this.briefList[i].num = res.data[arr[k]].data;
                  this.briefList[i].textValue = res.data[arr[k]].rate
                    ? res.data[arr[k]].rate
                    : res.data[arr[k]].converted == 0
                    ? -1
                    : res.data[arr[k]].converted;
                  if (res.data[arr[k]].hasOwnProperty("notConverted")) {
                    //学员数
                    this.briefList[i].notConverted =
                      res.data[arr[k]].notConverted == 0
                        ? -1
                        : res.data[arr[k]].notConverted;
                  }
                }
              } else {
                item.rate = "0%";
                item.num = "0";
                item.textValue = "0%";
              }
            }
          }
          // console.log(this.briefList);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 两个浮点数相乘
     * @param arg1
     * @param arg2
     * @return {number}
     */
    accMul(arg1, arg2) {
      let m = 0;
      const s1 = arg1.toString();
      const s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {
        // console.log(e)
      }
      try {
        m += s2.split(".")[1].length;
      } catch (e) {
        console.log(e);
      }
      return (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
      );
    },

    /**
     * 销售简报查看
     */
    reportClick(item) {
      if (item.type) {
        this.reportData.title = `销售简报-${item.title}`;
        this.reportData.placeholder = {
          leadsTip: "请输入线索名称",
          contactsTip: "请输入联系人姓名/手机/电话",
          customerTip: "请输入学员名称",
          contract: "请输入合同名称",
          receivables: "请输入回款编号",
          record: "",
        }[item.plaTip];
        this.reportData.crmType = item.type;
        this.reportData.params = this.getBaseParams();

        if (item.type == "record") {
          this.fieldReportList = [
            {
              label: "模块",
              prop: "crmType",
              width: 300,
            },
            {
              label: "新增跟进记录数",
              prop: "count",
            },
          ];
          this.reportData.request = crmQueryRecordConuntAPI;
          this.reportData.paging = false;
          this.reportData.sortable = false;
        } else {
          this.fieldReportList = null;
          this.reportData.request = crmIndexIndexListAPI;
          this.reportData.paging = true;
          this.reportData.sortable = "custom";

          // 合同金额回款金额 通过的
          if (
            item.field === "receivablesMoney" ||
            item.field === "contractMoney"
          ) {
            this.reportData.params.checkStatus = 1;

            // 合同金额 回款金额 加入 moneyType 1合同 2回款
            this.reportData.params.moneyType = {
              contractMoney: 1,
              receivablesMoney: 2,
            }[item.field];
          }
        }

        this.reportData.params.label = parseInt(item.labelValue);
        this.reportData.params.isUnable =
          item.field == "finalizedDealRateData" ? true : false;
        if (item.searchList) {
          this.reportData.params.searchList = item.searchList;
        }
        this.reportListShow = true;
      }
    },

    /**
     * 排序
     */
    getModelSort() {
      /**
       * 1 合同金额目标及完成情况
       * 2 数据汇总
       * 3 回款金额目标及完成情况
       * 4 业绩指标完成率 (回款金额)
       * 5 销售漏斗
       * 6 遗忘提醒
       * 7 排行榜
       */

      // crmIndexSortAPI().then(res => {
      //   console.log(res)
      //   const left = res.data.left || []
      //   const right = res.data.right || []

      //   // 2 回款和合同合并，展示保留其位置

      //   this.sortLeft = left.map(item => {
      //     console.log(item)
      //     item.component = components[item.modelId - 1]
      //     return item
      //   }).filter(item => {
      //     return item.isHidden == 0
      //   })

      //   this.sortRight = right.map(item => {
      //     item.component = components[item.modelId - 1]
      //     return item
      //   }).filter(item => {
      //     return item.isHidden == 0
      //   })
      // }).catch()
      const components = [
        "RankingStatistics",
        "PerformanceChart",
        "DataStatistics",
        "SaleStatistics",
        "DataStatistics",
        "",
        "SalesFunnel",
        "ForgetRemind",
      ];
      this.sortRight = components;
    },

    /**
     * 图标点击 目前仅商机漏斗
     */
    chartClick(chartData, data) {
      this.reportData.title = `销售漏斗-${data.name}`;
      this.reportData.placeholder = "请输入商机名称";
      this.reportData.crmType = "business";
      this.reportData.params = this.getBaseParams();
      this.reportData.params.entity = {
        formType: "business_type",
        name: "statusId",
        type: 1,
        values: [data.typeId, data.statusId],
      };
      this.fieldReportList = null;
      this.reportData.request = crmInstrumentSellFunnelBusinessListAPI;
      this.reportData.paging = true;
      this.reportData.sortable = "custom";
      this.reportData.params.label = 5;
      this.reportListShow = true;
    },
  },
};
</script>

<style scoped lang="scss">
.crm-workbench {
  width: 100%;
  min-width: 1200px;
  height: 100%;
  padding: 15px 20px 20px;
  position: relative;

  &__body {
    height: 100%;
    overflow: auto;
    padding-top: 55px;
  }

  .head {
    position: absolute;
    padding: 15px 20px;
    top: 0;
    right: 0;
    left: 0;
    background: #f5f6f9;
    z-index: 1;

    &__body {
      position: relative;
      .user-box {
        width: unset;
        height: 36px;
        padding: 4px 7px;
        border: 1px solid #e1e1e1;
        border-radius: $xr-border-radius-base;
        background-color: white;
        margin-right: 20px;
        display: flex;
        cursor: pointer;
        .user-icon {
          background: $xr-color-primary;
          color: white;
          padding: 5px 6px;
          border-radius: 50%;
        }
        .username {
          font-size: 12px;
          margin: 0 8px;
        }
      }
      .el-radio-group {
        /deep/ .el-radio-button__inner {
          font-size: 12px;
          padding: 11px 12px;
        }
      }
      /deep/ .type-select {
        height: 36px;
      }

      .sort-btn {
        position: absolute;
        right: 0;
        top: 0;
      }
    }
  }

  .brief-box {
    width: 100%;
    background-color: white;
    border: 1px solid #e6e6e6;
    border-radius: $xr-border-radius-base;
    .brief-title {
      padding: 15px 20px 0;
      .icon {
        color: #50cf9e;
        font-size: 18px;
      }
      .text {
        font-size: 16px;
        font-weight: bold;
        margin-left: 5px;
      }
    }
    .brief {
      width: 100%;
      padding: 10px 10px 14px 10px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;
      .brief-item {
        cursor: pointer;
        width: calc(25% - 20px);
        height: 88px;
        box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.08);
        border-radius: $xr-border-radius-base;
        margin: 10px;
        &:first-child {
          .brief-item__others {
            .rate {
              color: #333;
              font-size: 24px;
            }
          }
        }
        .brief-item__body {
          flex: 1;
          overflow: hidden;
          .icon-box {
            width: 36px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            border-radius: 50%;
            margin-right: 10px;
            margin-left: 15px;
            flex-shrink: 0;

            .icon {
              color: white;
              font-size: 19px;
            }
          }
          .info {
            overflow: hidden;
            .title {
              font-size: 13px;
            }
            .number {
              font-size: 23px;
              font-weight: bold;
              line-height: 1;
              margin-top: 8px;
              margin-right: 5px;
              // white-space: nowrap;
              // text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
        .brief-item__others {
          position: relative;
          width: 100px;
          text-align: center;
          padding: 0 3px;
          overflow: hidden;

          &:before {
            position: absolute;
            top: 7.5%;
            left: 0;
            content: "";
            width: 1px;
            height: 85%;
            background-color: #e6e6e6;
            display: block;
          }
          .text {
            font-size: 12px;
            margin-left: -5px;
          }
          .rate {
            font-size: 14px;
            color: #2bbf24;
            margin-top: 8px;

            .rate__icon {
              font-size: 12px;
            }
            &.bottom {
              color: #2bbf24;
            }
            &.top {
              color: #f24b4b;
            }
          }
        }
        &:hover {
          box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.2);
        }
      }
    }
  }

  .section {
    margin-top: 18px;
    .left {
      width: calc(60.5% - 20px);
      margin-right: 20px;
      &-content {
        height: 400px;
      }
    }
    .right {
      width: 39.5%;
      &-content {
        height: 400px;
      }
    }

    .left-content + .left-content,
    .right-content + .right-content {
      margin-top: 18px;
    }
  }
}
.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px 20px;
}
.lable {
  width: 70px;
}
.xh-structure-cell {
  width: 235px;
  margin-right: 15px;
}

</style>
<style>
  .xh-structure-cell > .el-popover__reference-wrapper > .el-popover__reference {
  background-color: #ffffff !important;
}
</style>
